package com.ksd.pug.clound.controller;

import com.ksd.pug.clound.pojo.SysUser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/consumer")
public class UserController {

    @Autowired
    private RestTemplate restTemplate;


    @GetMapping("/user/{id}")
    @HystrixCommand(fallbackMethod = "getUserFallback", commandProperties = {
        @HystrixProperty(name = HystrixPropertiesManager.FALLBACK_ENABLED, value = "false"),
        // 如果请求并发数达到该设置的值，请求会被拒绝和抛出异常并且fallback不会被调用 默认是：10秒
        @HystrixProperty(name = HystrixPropertiesManager.FALLBACK_ISOLATION_SEMAPHORE_MAX_CONCURRENT_REQUESTS, value = "15")
    })
    public SysUser getUser(@PathVariable("id") Long id) {
        // 1、调用者（消费者）：自身服务程序出现异常和故障就会走入fallback
        if (id == 1L) {
            throw new RuntimeException();
        }
        String url = "http://pug-hystrix-user-service/user/" + id;
        return restTemplate.getForObject(url, SysUser.class);//
    }

    /**
     * 细节1：方法返回值必须一模一样，
     * 细节2：参数也必须一模一样
     */
    public SysUser defaultFallback(Long id) {
        return new SysUser();
    }
}
